
<style>
    .table-text{
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }
</style>

<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
        管理
        <small>列表</small>
    </h1>
</section>

<!-- Main content -->
<section class="content" id="essay-viewpoint-app">

    <div class="row">
        <div class="col-md-2">
            <a v-show="show.list" class="btn btn-default" @click="getList">刷新</a>
            <a v-show="show.list" class="btn btn-info" @click="add">添加</a>
            <a v-show="show.edit" class="btn btn-danger" @click="show.edit = false;show.list=true">关闭</a>
        </div>
        <div class="col-md-10" v-show="show.list">
            <div class="col-md-2">
                <select class="form-control" v-model="page.catalog_id">
                    <option value="0">全部分类……</option>
                    <option v-for="c in catalogs" :value="c.id">{{c.name}}</option>
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-control" v-model="page.teacher_id">
                    <option value="-1">所有老师/来源……</option>
                    <option value="0">【转载】</option>
                    <option v-for="c in teachers" :value="c.id">{{c.realname}}</option>
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-control" v-model="page.column_id">
                    <option value="-1">全部…</option>
                    <option v-for="c in columns" :value="c.id">{{c.title}}</option>
                </select>
            </div>
        </div>
    </div>

    <div class="row" v-show="show.list">
        <div class="col-md-12">
            <table class="table table-responsive table-striped table-bordered">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>老师</th>
                    <th>标题</th>
                    <th>摘要</th>
                    <th>分类</th>
                    <th>专栏</th>
                    <th>时间</th>
                    <th>下架</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in list">
                    <td>{{item.id}}</td>
                    <td>{{item | Teacher}}</td>
                    <td><div class="table-text" style="width:10rem;" :title="item.title">{{item.title}}</div></td>
                    <td><div class="table-text" style="width:20rem;" :title="item.summary">{{item.summary}}</div></td>
                    <td>{{item.catalog_name || '-'}}</td>
                    <td>{{item.column_title || '-'}}</td>
                    <td>{{item.created | TimeFormat}}</td>
                    <td>{{item.hide ? '是' : ''}}</td>
                    <td>
                        <a class="btn btn-info btn-xs" @click="edit(item)">编辑</a>

                        <a v-if="!item.hide" class="btn btn-warning btn-xs" @click="hide(item)">下架</a>
                        <a v-if="item.hide" class="btn btn-primary btn-xs" @click="hide(item)">上架</a>

                        <span v-if="!item.hide">
                            <a v-if="item.recommend" class="btn btn-warning btn-xs" @click="recommend(item, 0)">取消推荐</a>
                            <a v-if="!item.recommend" class="btn btn-info btn-xs" @click="recommend(item, 1)">加推荐</a>
                        </span>

                        <a v-if="!item.hide" class="btn btn-info btn-xs" @click="positionAdd(item)">内容推荐</a>

                        <a v-if="item.hide" class="btn btn-danger btn-xs" @click="del(item)">删除</a>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr>
                    <td colspan="100">
                        <pagination :total="page.total" :limit="page.limit" :offset="page.offset" @turn="turnPage" ></pagination>
                    </td>
                </tr>
                <tr>
                    <td colspan="100">
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div class="row" v-show="show.edit">
        <div class="col-md-8 col-md-offset-2">
            <h3>编辑</h3>
            <div class="form" role="form">
                <div class="form-group has-warning">
                    <label>老师：</label>
                    <select class="form-control" v-model="edit_item.teacher_id">
                        <option value="0">转载……</option>
                        <option v-for="t in teachers" :value="t.id">{{t.realname}}</option>
                    </select>
                </div>

                <div class="form-group" v-if="0 == edit_item.teacher_id">
                    <label>转载来源：</label>
                    <input class="form-control" v-model="edit_item.ref_source.name" placeholder="来源网站名称">
                    <input class="form-control" v-model="edit_item.ref_source.url" placeholder="转载网页链接地址">
                    <div style="padding: 1rem; background: white"><img class="img-responsive" :src="edit_item.ref_source.logo"/></div>
                </div>

                <div class="form-group">
                    <label>类型：<a class="fa fa-refresh" @click="getCatalogs"></a></label>
                    <select class="form-control" v-model="edit_item.catalog_id">
                        <option value="0">不分类</option>
                        <option v-for="(c,i) in catalogs" v-if="c.parent_id>0" :value="c.id">{{c.name}}</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>标题：</label>
                    <input class="form-control" v-model="edit_item.title">
                </div>


                <div class="form-group">
                    <label>摘要(100字，可用于seo搜索)：</label>
                    <textarea style="width:100%;height:50px;resize:vertical" v-model="edit_item.summary" maxlength="100"></textarea>
                </div>

                <div class="form-group">
                    <label>封面：</label>
                    <file-uploader style="height:80px" v-model="edit_item.cover" filetype="image" oss="true" policyUrl="/alioss/get_policy"></file-uploader>
                </div>

                <div class="form-group">
                    <label>内容：</label>
                    <ck-editor v-model="edit_item.content" :tag="edit_tag"></ck-editor>
                </div>

                <div class="form-group" :class="{'has-error': !edit_item.tags || edit_item.tags.length < 2}">
                    <label>标签(至少两个，每个最多5个字)</label>
                    <div >
                        <a class="btn btn-primary btn-xs" @click=" addTag ">添加</a>
                        <input v-model="tmp.tag" maxlength="5" placeholder="输入标签">
                        <ul>
                            <li v-for="(t,i) in edit_item.tags">
                                <span>{{t}}</span>
                                <a class="btn btn-danger btn-xs" @click="edit_item.tags.splice(i,1)"><i class="fa fa-remove"></i></a>
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="form-group">
                    <label>股票 (请输入要选择的股票代码) </label>
                    <div >
                        <a class="btn btn-primary btn-xs" @click="addStock">添加</a>
                        <input v-model="tmp.stock" maxlength="8" placeholder=" 输入股票代码">
                        <ul>
                            <li v-for="(t,i) in edit_item.stocks">
                                <span>{{t}}</span>
                                <a class="btn btn-danger btn-xs" @click="edit_item.stocks.splice(i,1)"><i class="fa fa-remove"></i></a>
                            </li>
                        </ul>
                    </div>
                </div>

                <div class="form-group" v-if="(edit_item.catalog_id==bindCourseCol.internalReferenceId) || (edit_item.catalog_id==bindCourseCol.researchReportId)">
                    <label>绑定课程（可选多个）：<a class="btn btn-xs" @click="getCurriculum(edit_item.catalog_id)"><i class="fa fa-refresh"></i></a></label>
                    <div>
                        <div class="col-md-12">
                            <a class="btn btn-warning btn-xs" @click="clearBindCourse">清空</a>
                            <!--<a class="btn btn-info btn-xs" @click="resetBindCourse">重置</a>-->
                        </div>
                        <select class="form-control" size="10" multiple v-model="edit_item.bind_course">
                            <option v-for="c in curriculumList" :value="c.id">[{{c.id}}][{{c.curriculum_type_name}}]{{c.name}} / &yen; {{c.price}}</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <a class="btn btn-primary" @click="save">发表</a>
                    <a class="btn btn-default" @click="show.edit=false;show.list=true">关闭</a>
                </div>
            </div>
        </div>
    </div>

    <!--内容推荐-->
    <div class="row" v-show="show.position">
        <div class="box-header">
            <h3>内容推荐</h3>
        </div>
        <div class="box-body">
            <position-add v-model="positionData" :item_type="1" item_url="/specialColumn/messageDetail/" ref="positionModal"></position-add>
        </div>
        <div class="box-footer">
            <button type="button" class="btn btn-primary pull-right" @click="positionSave()">推荐</button>
            <button type="button" class="btn btn-default pull-left" @click="show.position=false;show.list=true">取消</button>
        </div>
    </div>
    <!--内容推荐 /-->
</section>
<!-- /.content -->



<script>
    function RefSource() {
        this.name = '';
        this.url = '';
        this.logo = '';
    }
    function Essay(teacher_id) {
        this.teacher_id = teacher_id;
        this.ref_source = new RefSource();
        this.content = '';
        this.tags = [];
        this.catalog_id = 0;
        this.stocks=[];
        this.bind_course = []
    }
    var essay_viewpoint_app = new Vue({
        el: '#essay-viewpoint-app',
        data: {
            list: [],
            edit_item: new Essay(0),
            edit_content: null,
            catalogs: [],
            columns: [],
            curriculumList: [],
            page: {
                total: 0,
                limit: 10,
                offset: 0,
                category: 3,
                catalog_id: 0,
                teacher_id: -1,
                column_id: -1,
            },
            teachers: [],
            show: {
                list: true,
                edit: false,
                position: false
            },
            tmp: {
                tag: '',
                stock:''
            },
            edit_tag: Date.now(),
            positionData: {},  //内容推荐数据
            bindCourseCol:{ // 允许绑定课程的栏目
                internalReferenceId:window.internalReferenceId,
                researchReportId:window.researchReportId
            }
        },
        created: function () {
            ajax({
                uri: '/common/teacher_names',
                success: function (resp) {
                    this.teachers = resp.data;
                }.bind(this)
            });
            this.getCatalogs();
            this.getColumns();
            this.getList();
        },
        methods: {
            getList: function () {
                ajax({
                    uri: '/essays/list',
                    data: this.page,
                    success: function(resp){
                        resp.list.forEach(function (val, i) {
                            val.tags = val.tags.split(',');
                            if (0 == val.teacher_id) {
                                try{
                                    val.ref_source = JSON.parse(val.ref_source);
                                }catch (ex){console.log('id='+val.id+'解析来源数据失败', ex)}
                            }
                        });
                        this.list = resp.list;
                        this.page.total = resp.total;
                    }.bind(this)
                });
            },
            getCatalogs: function () {
                ajax({
                    uri: '/essays/catalog_list',
                    data: {rows: 100, page: 1},
                    success: function (resp) {
                        this.catalogs = resp.data;
                    }.bind(this)
                })
            },
            getColumns: function () {
                ajax({
                    uri: '/common/column_names',
                    data: {teacher_id: this.page.teacher_id},
                    success: function (resp) {
                        this.columns = resp.data;
                    }.bind(this)
                })
            },
            getCurriculum(catalog_id){
                var _catalog_id = catalog_id || 0;
                ajax({
                    uri: '/bills/curriculum_names',
                    data:{
                        'bindArticleColId':_catalog_id
                    },
                    success: function (resp) {
                        this.curriculumList = resp.data;
                    }.bind(this)
                })
            },
            // 清空选中的绑定课程
            clearBindCourse: function () {
                this.edit_item.bind_course = [];
            },
            // 重置绑定课程数据
            /*resetBindCourse: function () {
                this.edit_item = Object.assign(new Essay(this.edit_item.teacher_id), this.edit_item);
            },*/
            add: function () {
                this.edit_item = new Essay(0);
                this.show.list = false;
                this.show.edit = true;
                this.edit_tag = Date.now();
            },
            edit: function (item) {
                this.edit_item = item;
                this.show.list = false;
                this.show.edit = true;
                this.edit_tag = Date.now();
            },
            save: function () {
                this.edit_item.category = this.page.category;

                var item = {};
                for (var p in this.edit_item) {
                    item[p] = this.edit_item[p];
                }
                if (!item.content) {
                    alert('请完善内容！');
                    return;
                }
                if ((item.catalog_id==this.bindCourseCol.internalReferenceId)||(item.catalog_id==this.bindCourseCol.researchReportId)) {
                    if (!item.bind_course || item.bind_course==''){
                        alert('请选择要绑定的课程！');
                        return false;
                    }
                }

                item.tags = item.tags.join(',');
                if (item.teacher_id == 0) item.ref_source = JSON.stringify(item.ref_source);

                ajax({
                    uri: '/essays/save',
                    data: item,
                    success: function(resp){
                        this.edit_item = {};
                        this.show.list = true;
                        this.show.edit = false;
                        this.getList();
                    }.bind(this)
                });
            },
            del: function (item) {
                ajax({
                    uri: '/essays/del',
                    data: {id: item.id},
                    success: function(resp){
                        this.getList();
                    }.bind(this)
                });
            },
            hide: function (item) {
                item.hide = !item.hide;
                ajax({
                    uri: '/essays/hide',
                    data: { id: item.id, hide: item.hide ? 1 : 0 },
                    success: function (resp) {
                        console.log(resp)
                    }.bind(this)
                });
            },
            recommend: function (item, r) {
                ajax({
                    uri: '/essays/recommend',
                    data: {id: item.id, recommend: r},
                    success: function (resp) {
                        this.getList();
                    }.bind(this)
                })
            },
            turnPage: function (offset) {
                this.page.offset = offset;
            },
            addTag: function () {
                if (!this.tmp.tag) return;
                this.edit_item.tags.push(this.tmp.tag);
                this.tmp.tag='';
            },
            addStock: function () {
                if (!this.tmp.stock) return;
                this.edit_item.stocks.push(this.tmp.stock);
                this.tmp.stock='';
            },
            /* 内容推荐 */
            positionAdd: function (item) {
                let self = this;
                this.positionData = {
                    itemId: item.id,
                    itemTitle: item.title,
                    itemImg: item.cover
                };

                this.show.list = false;
                self.show.position = true;
                setTimeout(function () {
                    self.$refs.positionModal.loadData(self.positionData);
                }, 50);
            },
            positionSave: function () {
                let self = this;
                self.$refs.positionModal.save(function () {
                    this.show.list = true;
                    self.show.position = false;
                });
            }
            /* 内容推荐 end */
        },
        filters: {
            Teacher: function (item) {
                var id = item.teacher_id;
                if (0 == id) {
                    return '【'+(item.ref_source.name || '')+'】';
                }
                var teachers = essay_viewpoint_app.teachers;
                for (var i=0; i<teachers.length; i++) {
                    var t = teachers[i];
                    if (t.id == id) {
                        return t.realname;
                    }
                }
                return '';
            },
            TimeFormat: function (time) {
                if (time) {
                    return new Date(time).format('yyyy-mm-dd hh:ii')
                }
                return time;
            }
        },
        watch: {
            'page.offset': function (nv, ov) {
                this.getList();
            },
            'page.catalog_id': function (nv, ov) {
                this.getList();
            },
            'page.teacher_id': function (nv, ov) {
                this.getList();
                this.getColumns();
            },
            'page.column_id': function (nv, ov) {
                this.getList();
            },
            'edit_item.ref_source.url': function (nv, ov) {
                if (!nv) return;
                var res = parseUrl(nv);
                this.edit_item.ref_source.logo = res.protocol + '//' + res.host + '/favicon.ico';
            },
            'edit_item.catalog_id': function (nv, ov) {
                if (!nv) return;
                this.getCurriculum(nv);
            }
        },
    })
</script>